//
//  WPReadingAudioPlayerVC.m
//  wobingwoyi
//
//  Created by WGP on 2017/1/12.
//  Copyright © 2017年 WGP. All rights reserved.
//

#import "WPReadingAudioPlayerVC.h"

@interface WPReadingAudioPlayerVC ()

@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)UIButton *backBtn;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UILabel *currentLabel;
@property(nonatomic,strong)UIButton *deleteBtn;
@property(nonatomic,strong)UIButton *playOrPause;

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,copy)NSString *totalTimeLength;

@end

@implementation WPReadingAudioPlayerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB_COLOR(31, 33, 36);
    [self setupUI];
}

-(void)setupUI
{
    //支持声音外放
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    //创建播放器层
    AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame=self.view.frame;
    playerLayer.videoGravity=AVLayerVideoGravityResizeAspect;//视频填充模式
    [self.view.layer addSublayer:playerLayer];
    
    [self bgImageView];
    [self backBtn];
    [self timeLabel];
    [self deleteBtn];
    [self playOrPause];
}

/**
 *  初始化播放器
 *
 *  @return 播放器对象
 */
-(AVPlayer *)player
{
    if (!_player)
    {
        AVPlayerItem *playerItem=[self getPlayItem];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
        
        [self addNotification];
        [self addProgressObserver];
        [self addObserverToPlayerItem:playerItem];
    }
    return _player;
}
/**
 *  根据视频索引取得AVPlayerItem对象
 *
 *  @param videoIndex 视频顺序索引
 *
 *  @return AVPlayerItem对象
 */
-(AVPlayerItem *)getPlayItem
{
    //    NSString *urlStr = @"http://192.168.1.112:8080/pic/0fc71a7a-2cd5-4a32-8763-b7a653dfd4d0.mp4";
    //    urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //    NSURL *url=[NSURL URLWithString:urlStr];
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:self.url];
    return playerItem;
}

-(UIButton *)backBtn
{
    if (_backBtn == nil)
    {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setTitle:@"    " forState:UIControlStateNormal];
        [_backBtn setImage:[UIImage imageNamed:@"audio_back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_backBtn];
        
        [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(15);
            make.top.equalTo(self.view).offset(30);
            make.height.mas_equalTo(30);
        }];
    }
    return _backBtn;
}

-(UILabel *)timeLabel
{
    if (_timeLabel == nil)
    {
        _timeLabel = [UILabel new];
        _timeLabel.textColor = [UIColor whiteColor];
        _timeLabel.font = [UIFont systemFontOfSize:18];
        _timeLabel.textAlignment = NSTextAlignmentRight;
        _timeLabel.text = @"00:00:00";
        [self.view addSubview:_timeLabel];
        
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.backBtn);
            make.right.equalTo(self.view).offset(-15);
        }];
    }
    return _timeLabel;
}

-(UILabel *)currentLabel
{
    if (_currentLabel == nil)
    {
        _currentLabel = [UILabel new];
        UIFont *font = [UIFont fontWithName:@"PingFangSC-Light"size:60];//这个是9.0以后自带的平方
        if(font==nil)
        {
            
            font = [UIFont fontWithName:@"STHeitiSC-Light"size:60];
        }
        _currentLabel.font = font;
        _currentLabel.text = @"00:00:00";
        _currentLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:_currentLabel];
        
        CGFloat offset = (SCREEN_HEIGHT/667.0)*175;
        [_currentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(offset);
        }];
    }
    return _currentLabel;
}

-(UIButton *)playOrPause
{
    if (_playOrPause == nil)
    {
        _playOrPause = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playOrPause setBackgroundImage:[UIImage imageNamed:@"reading_audio_play"] forState:UIControlStateNormal];
        //        [_playOrPause setBackgroundImage:[UIImage imageNamed:@"audio_stop"] forState:UIControlStateNormal];
        [_playOrPause addTarget:self action:@selector(playOrPauseBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:_playOrPause];
        
        CGFloat offset = (SCREEN_HEIGHT/667.0)*400;
        [_playOrPause mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(offset);
        }];
        
    }
    return _playOrPause;
}

#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification
{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
-(void)playbackFinished:(NSNotification *)notification
{
    [self.player pause];
    [self.playOrPause setBackgroundImage:[UIImage imageNamed:@"reading_audio_play"] forState:UIControlStateNormal];
}

#pragma mark - 监控
/**
 *  给播放器添加进度更新
 */
-(void)addProgressObserver
{
    AVPlayerItem *playerItem=self.player.currentItem;
    
    //这里设置每秒执行一次
    __weak typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        float total=CMTimeGetSeconds([playerItem duration]);
        
        weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@",[NSString timeHourStrWithDurations:total]];
        weakSelf.currentLabel.text = [NSString stringWithFormat:@"%@",[NSString timeHourStrWithDurations:current]];
    }];
}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem
{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem
{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"])
    {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay)
        {
           
            self.totalTimeLength = [NSString timeHourStrWithDurations:CMTimeGetSeconds(playerItem.duration)];
            self.timeLabel.text = [NSString stringWithFormat:@"%@",self.totalTimeLength];
        }
    }
    else if([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        WPLog(@"共缓冲：%.2f",totalBuffer);
    }
}

#pragma mark - 按钮响应事件
-(void)playOrPauseBtnDidClick:(UIButton *)btn
{
    CMTime currentTime = _player.currentItem.currentTime;
    CMTime durationTime = _player.currentItem.duration;
    
    if(self.player.rate==0)
    {
        //说明时暂停
        //        [btn setBackgroundImage:[UIImage imageNamed:@"audio_stop"] forState:UIControlStateNormal];
        if (currentTime.value == durationTime.value)
        {
            [self.player.currentItem seekToTime:CMTimeMake(0, 1)];
        }
        [btn setBackgroundImage:[UIImage imageNamed:@"audio_stop"] forState:UIControlStateNormal];
        [self.player play];
    }
    else if(self.player.rate==1)
    {
        //正在播放
        [self.player pause];
        [btn setBackgroundImage:[UIImage imageNamed:@"reading_audio_play"] forState:UIControlStateNormal];
    }
}

-(void)backBtnDidClick
{
    if (self.backBlock)
    {
        [self.player pause];
        self.backBlock();
    }
}

-(void)dealloc
{
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
